﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Text;

namespace RapidRepository
{
    /// <summary>
    /// Helper class for saving, loading and deleting files.
    /// </summary>
    public static class File
    {
        #region Declarations

        const string fileDirectory = "Files";
        const string fileExtension = ".txt"; 

        #endregion

        #region Save

        /// <summary>
        /// Saves the specified file data.
        /// </summary>
        /// <param name="fileData">The file data.</param>
        /// <returns>A Guid identity for the file, this can be used to load and delete the file.</returns>
        public static Guid Save(string fileData)
        {
            Contract.Requires("fileData", !string.IsNullOrEmpty(fileData));

            Guid fileId = Guid.NewGuid();

            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    CreateDirectoryIfNotExists(store, FileManager.rapidRepositoryDirectory);

                    string fileDirectoryPath = Path.Combine(FileManager.rapidRepositoryDirectory, fileDirectory);

                    CreateDirectoryIfNotExists(store, fileDirectoryPath);

                    string filePath = Path.Combine(fileDirectoryPath, CreateFileName(fileId));

                    using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, store))
                    {
                        using (StreamWriter stream = new StreamWriter(fileStream))
                        {
                            stream.Write(fileData);
                        }
                    }
                }
            }
            catch
            {
                throw;
            }

            return fileId;
        } 

        #endregion

        #region Load

        /// <summary>
        /// Loads the specified file id.
        /// </summary>
        /// <param name="fileId">The file id.</param>
        /// <returns>AThe file content as a string</returns>
        public static string Load(Guid fileId)
        {
            Contract.Requires("fileId", fileId != Guid.Empty);

            try
            {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string fileDirectoryPath = Path.Combine(FileManager.rapidRepositoryDirectory, fileDirectory);

                    if (!store.DirectoryExists(fileDirectoryPath))
                    {
                        return string.Empty;
                    }

                    return GetFileContent(store, fileDirectoryPath, CreateFileName(fileId));
                }
            }
            catch
            {
                throw;
            }
        }

        #region Private methods

        private static string GetFileContent(IsolatedStorageFile store, string typeDirectoryPath, string fileName)
        {
            string filePath = Path.Combine(typeDirectoryPath, fileName);

            using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Open, store))
            {
                using (TextReader reader = new StreamReader(fileStream))
                {
                    return reader.ReadToEnd();
                }
            }
        } 

        #endregion

        #endregion

        #region Delete

        public static void Delete(Guid fileId)
        {
            Contract.Requires("fileId", fileId != Guid.Empty);

            try
            {
                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string fileDirectoryPath = Path.Combine(FileManager.rapidRepositoryDirectory, fileDirectory);

                    string filePath = Path.Combine(fileDirectoryPath, CreateFileName(fileId));

                    store.DeleteFile(filePath);
                }
            }
            catch
            {
                throw;
            }
        } 

        #endregion

        #region Helpers

        private static void CreateDirectoryIfNotExists(IsolatedStorageFile store, string directory)
        {
            if (!store.DirectoryExists(directory))
            {
                store.CreateDirectory(directory);
            }
        }

        private static string CreateFileName(Guid entityId)
        {
            return string.Format("{0}{1}", entityId.ToString(), fileExtension);
        }

        #endregion
    }
}
